#include <iostream>
using namespace std;
#include <signal.h>
#include <assert.h>
#include <unistd.h>

void PrintSig(sigset_t pending)
{
    cout << "PrintSig: ";
    for (int i = 31; i >= 1; i--) // signo 从 1 到 31
    {
        if (sigismember(&pending, i))
            cout << "1";
        else
            cout << "0";
    }
    cout << endl;
}

void handler(int signo)
{
    // (void)signo; // 不处理 2 号信号
    sigset_t pending;
    sigemptyset(&pending);
    sigpending(&pending);

    PrintSig(pending);
}

int main()
{
    // signal(SIGINT, handler);
    // 1. 屏蔽 2 号信号
    sigset_t block;
    sigset_t oblock;
    sigemptyset(&block);
    sigemptyset(&oblock);

    // int n = sigaddset(&block, SIGINT);
    // assert(n == 0); // success return 0, else return -1

    for (int i = 1; i <= 31; i++)
    {
        int n = sigaddset(&block, i);
        assert(n == 0);
    }

    sigprocmask(SIG_SETMASK, &block, &oblock);
    cout << "block SIGINT success ..." << endl;
    cout << "process id: " << getpid() << endl;

    int cnt = 0;
    while (1)
    {
        // 2. 获取进程的 pending 图
        sigset_t pending;
        sigemptyset(&pending);

        int n = sigpending(&pending); // 获取当前pending集合
        assert(n == 0);

        // 3. 打印 pending图
        PrintSig(pending);
        ++cnt;

        // 4. 对 SIGINT 信号恢复
        if (cnt == 20)
        {
            cout << "对 SIGINT 恢复" << endl;
            n == sigprocmask(SIG_UNBLOCK, &block, &oblock);
            assert(n == 0);
        }
        sleep(1);
    }

    return 0;
}